package com.csp.main.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csp.common.utils.R;
import com.csp.main.entity.ShopCart;
import com.csp.main.service.ShopCartService;
import com.csp.main.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author csp
 * @since 2022-06-08
 */
@RestController
@RequestMapping("/main/shop-cart")
public class ShopCartController {

    @Autowired
    private ShopCartService shopCartService;

    @GetMapping("/list")
    public R getList(HttpServletRequest request){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String userId = JWTUtils.validateToken(token);
        QueryWrapper<ShopCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<ShopCart> list = shopCartService.list(queryWrapper);
        return R.ok().data("rows",list);
    }

    @GetMapping("/add/{comId}")
    public R add(HttpServletRequest request,@PathVariable String comId){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String userId = JWTUtils.validateToken(token);
        ShopCart data = new ShopCart();
        data.setUserId(userId);
        data.setComId(comId);
        boolean save = shopCartService.save(data);
        return save?R.ok():R.error();
    }

    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable String id){
        boolean b = shopCartService.removeById(id);
        return b?R.ok():R.error();
    }

}

